package com.salt.modules.sys.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * HTTP请求封装，建议直接使用sdk的API
 */
public class HttpHelper {

    private static Logger logger = LoggerFactory.getLogger(HttpHelper.class);

    public static JSONObject httpsGet(String url) throws Exception {
        URL url1 = new URL(url);
        URI uri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = new SSLClient();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                String str = "request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url;
                logger.info("发送网络请求：");
                logger.info(str);
                throw new Exception("网络请求失败");
            }
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                String resultStr = EntityUtils.toString(entity, "utf-8");

                logger.info("请求结果为：");

                logger.info(resultStr);

                JSONObject result = JSON.parseObject(resultStr);

                if (result != null) {
                    return result;
                } else {
                    logger.info("异常了");
                    throw new Exception("请求异常");
                }
            } else {
                logger.info("请求结果为空");
                throw new Exception("请求结果为空");
            }
        } catch (IOException e) {
            logger.info("异常了:");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw new Exception("异常了:" + e.getMessage());
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static JSONObject httpGet(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                String str = "request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url;
                logger.info("发送网络请求：");
                logger.info(str);
                throw new Exception("网络请求失败");
            }
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                String resultStr = EntityUtils.toString(entity, "utf-8");

                logger.info("请求结果为：");

                logger.info(resultStr);

                JSONObject result = JSON.parseObject(resultStr);

                if (result != null) {
                    return result;
                } else {
                    logger.info("异常了");
                    throw new Exception("请求异常");
                }
            } else {
                logger.info("请求结果为空");
                throw new Exception("请求结果为空");
            }
        } catch (IOException e) {
            logger.info("异常了:");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
            throw new Exception("异常了:" + e.getMessage());
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    public static JSONObject httpsPost(String url, String data, Map<String, String> map) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = new SSLClient();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        if(map != null){
            for (String s : map.keySet()) {
                httpPost.addHeader(s, map.get(s));
            }
        }

        try {
            StringEntity requestEntity = new StringEntity(data, "utf-8");
            requestEntity.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
            httpPost.setEntity(requestEntity);

            logger.info("发送网络请求：");
            logger.info(url);
            logger.info(data);

            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                logger.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                logger.info("返回的数据为:");
                logger.info(resultStr);
                JSONObject result = JSON.parseObject(resultStr);
                return result;
            } else {
                logger.info("返回的数据为空");
            }
        } catch (IOException e) {
            logger.info("异常了");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static JSONObject httpPost(String url, JSONObject data, Map<String, String> map) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");



        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");
            requestEntity.setContentType("text/json");
            requestEntity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

            httpPost.setEntity(requestEntity);

            if(map != null){
                for (String s : map.keySet()) {
                    httpPost.addHeader(s, map.get(s));
                }
            }

            logger.info("发送网络请求：");
            logger.info(url);
            logger.info(data.toJSONString());

            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                logger.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                logger.info("返回的数据为:");
                logger.info(resultStr);
                JSONObject result = JSON.parseObject(resultStr);
                return result;
            } else {
                logger.info("返回的数据为空");
            }
        } catch (IOException e) {
            logger.info("异常了");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String[] httpPostFaceBook(String url, JSONObject data) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");

        try {
            StringEntity requestEntity = new StringEntity(JSON.toJSONString(data), "utf-8");

            httpPost.setEntity(requestEntity);

            logger.info("发送网络请求：");
            logger.info(url);
            logger.info(data.toJSONString());

            response = httpClient.execute(httpPost, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                logger.info("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url);
                return null;
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String resultStr = EntityUtils.toString(entity, "utf-8");
                logger.info("返回的数据为:");
                logger.info(resultStr);
                return resultStr.split(",");
            } else {
                logger.info("返回的数据为空");
            }
        } catch (IOException e) {
            logger.info("异常了");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String[] httpGetFacebook(String url, JSONObject params) throws Exception {

        if (params != null) {
            Set<String> keys = params.keySet();

            url += "?";

            for (String key : keys) {
                url += key + "=" + params.getString(key) + "&";
            }

        }

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpGet.setConfig(requestConfig);

        try {
            response = httpClient.execute(httpGet, new BasicHttpContext());

            if (response.getStatusLine().getStatusCode() != 200) {

                String str = "request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url;
                logger.info("发送网络请求：");
                logger.info(str);
                throw new Exception("网络请求失败");
            }
            HttpEntity entity = response.getEntity();

            if (entity != null) {

                String resultStr = EntityUtils.toString(entity, "utf-8");

                logger.info("请求结果为：");

                logger.info(resultStr);

                return resultStr.split(",");


            } else {
                logger.info("请求结果为空");
                return null;
            }
        } catch (IOException e) {
            logger.info("异常了:");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();

        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static JSONObject httpPostFrom(String url,  List<NameValuePair> parameters) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");



        try {
            HttpEntity entity = new UrlEncodedFormEntity(parameters,"utf-8");

            httpPost.setEntity(entity);

            response = httpClient.execute(httpPost, new BasicHttpContext());

        } catch (IOException e) {
            logger.info("异常了");
            logger.info(e.getMessage());
            logger.info("request url=" + url + ", exception, msg=" + e.getMessage());
            System.out.println("request url=" + url + ", exception, msg=" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (response != null) try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
